package com.njupt.Tree;

import java.util.ArrayList;
import java.util.Deque;
import java.util.LinkedList;
import java.util.List;

/**
 * @Author: wujiaming
 * @CreateTime: 2024/11/19 16:06
 * @Description: 中序遍历非递归算法
 * @Version: 1.0
 */


public class InorderTraversalNoRecursion {

    public List<Integer> inorderTraversalNoRecursion(TreeNode root) {
        List<Integer> result = new ArrayList<>();
        Deque<TreeNode> stack = new LinkedList<>();
        TreeNode cur = root;
        while(cur != null || !stack.isEmpty()){
            if(cur != null){
                stack.push(cur);
                cur = cur.left;
            }else {
                cur = stack.pop();
                result.add(cur.val);
                cur = cur.right;
            }
        }

        return result;
    }

    public static void main(String[] args) {
        TreeNode root = new TreeNode(1);
        TreeNode node1 = new TreeNode(2);
        TreeNode node2 = new TreeNode(3);
        root.right = node1;
        node1.left = node2;
        InorderTraversalNoRecursion test = new InorderTraversalNoRecursion();
        List<Integer> list = test.inorderTraversalNoRecursion(root);
        System.out.println(list.toString());
    }
}
